package com.enjoyor.health.HGPT.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.enjoyor.health.HGPT.core.dto.WatchDataDto;
import com.enjoyor.health.HGPT.core.entity.CommonInfo;
import com.enjoyor.health.HGPT.core.entity.UserInfo;
import com.enjoyor.health.HGPT.core.entity.UserInfoMiniapp;
import com.enjoyor.health.HGPT.core.entity.WatchData;
import com.enjoyor.health.HGPT.core.service.ICommonInfoService;
import com.enjoyor.health.HGPT.core.service.IUserInfoMiniappService;
import com.enjoyor.health.HGPT.core.service.IUserInfoService;
import com.enjoyor.health.HGPT.core.service.IWatchDataService;
import com.enjoyor.health.HGPT.web.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zhu Min
 * @date 2023/12/13 14:44
 */
@Slf4j
@Service
public class BizWatchService {

    @Autowired
    private IWatchDataService watchDataService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoMiniappService userInfoMiniappService;
    @Autowired
    private ICommonInfoService commonInfoService;

    public CodeEnum save(WatchDataDto dataDto){
        String openId = dataDto.getOpenId();
        String userId = dataDto.getUserId();
        if (StringUtils.isNotBlank(dataDto.getOpenId()) && StringUtils.isBlank(dataDto.getUserId())){
            //查找userID，因为app用这个
            UserInfo userInfo = userInfoService.getUserInfoFromOpenId(dataDto.getOpenId());
            if (userInfo != null){
                userId = userInfo.getId();
            }else {
                log.warn("用户不存在，openId {}", dataDto.getOpenId());
                return CodeEnum.NO_USER_INFO;
            }
        }
        if (StringUtils.isNotBlank(dataDto.getUserId()) && StringUtils.isBlank(dataDto.getOpenId())){
            List<UserInfoMiniapp> userInfoMiniappList = userInfoMiniappService.getByUserId(dataDto.getUserId());
            if (userInfoMiniappList != null){
                openId = userInfoMiniappList.get(0).getOpenId();
            }else {
                log.warn("用户{}无对应OPENID", dataDto.getUserId());
            }
        }

        JSONArray dataArray = JSONArray.parseArray(dataDto.getData());
        for (int i = 0; i < dataArray.size(); i++) {
            try {
                JSONObject json = dataArray.getJSONObject(i);
                Long timestamp = json.getLong("startTime");
                if (timestamp != null && (timestamp+"").length()==10){
                    timestamp = Long.parseLong(timestamp+"000");
                }
                WatchData watchData = new WatchData();
                watchData.setDataId(IdUtil.simpleUUID());
                watchData.setType(dataDto.getType());
                watchData.setStorageTime(LocalDateTime.now());
                watchData.setData(json.toJSONString());
                watchData.setOpenId(openId);
                watchData.setUserId(userId);
                watchData.setDeviceId(dataDto.getDeviceId());
                watchData.setTime(LocalDateTimeUtil.of(timestamp));

                UpdateWrapper<WatchData> wrapper = Wrappers.update();
                wrapper.eq("time", watchData.getTime())
                        .eq("type", dataDto.getType())
                        .eq("user_id", userId)
                        .eq("device_id", dataDto.getDeviceId())
                        .set("data", watchData.getData())
                        .set("open_id", openId)
                        .set("storage_time", watchData.getStorageTime());
                watchDataService.saveOrUpdate(watchData, wrapper);
            }catch (Exception e){
                log.error("数据插入出错", e);
                return CodeEnum.ERROR;
            }
        }
        return CodeEnum.SUCCESS;
    }

    public List<JSONObject> getList(String type, String openId, String userId, String deviceId){
        if (StringUtils.isNotBlank(openId) && StringUtils.isBlank(userId)){
            userId = userInfoMiniappService.getUserInfoMiniappByOpenId(openId).getUserId();
        }
        List<WatchData> watchDataList = watchDataService.getWatchDataList(type, userId, deviceId);
        return watchDataList.stream().map(x->JSONObject.parseObject(x.getData()))
                .collect(Collectors.toList());
    }

    public List<CommonInfo> getCommonInfoByType(String type){
        return commonInfoService.getByType(type);
    }

}
